<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import {addMenu, getMenuById, updateMenu} from "@/api/menu.js";
// type 是add就是添加 是edit就是修改
const {id, type} = defineProps({
  id: {
    type: Number,
    default: undefined
  },
  type: {
    type: String,
    default: 'add'
  }
})

onMounted(() => {
  if (id !== 0 && type === 'edit') {
    getMenu(id)
  } else {
    form.value.pid = id
  }
})
//获取菜单信息
const getMenu = async (id) => {
  const {code, data, msg} = await getMenuById(id);
  if (code !== 200) {
    ElMessage({
      type: 'error',
      message: msg,
    })
    window.location.reload();
    return
  }
  form.value = data
}
//表单
const form = ref({
  id: undefined,
  pid: undefined,
  name: undefined,
  icon: undefined,
  path: undefined,
  sort: 0,
  status: 1,
})

//提交表单
const onSubmit = async () => {
  if (type === 'add') {
    await add()
  } else {
    await edit()
  }
}
//事件
const emit = defineEmits(['success'])
//添加菜单
const add = async () => {
  const {code, msg} = await addMenu(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}
//修改菜单
const edit = async () => {
  const {code, msg} = await updateMenu(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}
</script>

<template>
  <el-form label-width="100px">
    <el-form-item required label="菜单名">
      <el-input v-model="form.name" placeholder="请输入菜单名"></el-input>
    </el-form-item>
    <el-form-item label="路径">
      <el-input v-model="form.path" placeholder="请输入路径"></el-input>
    </el-form-item>
    <el-form-item required label="排序">
      <el-input type="number" v-model="form.sort" placeholder="数字越大排序越靠前"></el-input>
    </el-form-item>
    <el-form-item required label="图标">
      <el-popover placement="top-start" :width="500" trigger="hover">
        <template #reference>
          <el-button v-if="!form.icon">选择</el-button>
          <el-button v-else :icon="form.icon"></el-button>
        </template>
        <span style="margin: 10px;cursor: pointer" @click="form.icon = item.name" v-for="item in ElementPlusIconsVue"><Component
            style="width: 20px;height: 20px;" :is="item"></Component></span>
      </el-popover>

    </el-form-item>
    <el-form-item required label="显示状态" v-if="type === 'edit'">
      <el-radio-group v-model="form.status" >
        <el-radio :value="1">显示</el-radio>
        <el-radio :value="0">隐藏</el-radio>
      </el-radio-group>
    </el-form-item>
  </el-form>
  <div style="text-align: right; margin-top: 20px">
    <el-button type="primary" @click="onSubmit">提交</el-button>
  </div>

</template>

<style lang="scss">
.el-popover {
  height: 300px;
  overflow: auto;
}
</style>